package code._14thread._04control;

import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SecurityStop {
    public static void main(String[] args) {
        SecurityStopThread t = new SecurityStopThread();
        t.start();
        for (int i = 0; i < 3; i++) {
            System.out.println("main-----"+i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        t.flag=false;
    }
}

class SecurityStopThread extends Thread{
    boolean flag=true;

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            if(flag){
                System.out.println(getName()+"-------"+i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }else {
                FileWriter fileWriter=null;
                try {
                    fileWriter= new FileWriter("fileTest\\log.txt");
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String data = sdf.format(new Date());
                    String threadName=getName();
                    fileWriter.write(data+threadName+"发生了中断！");
                    fileWriter.flush();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }finally {
                    if(fileWriter!=null){
                        try {
                            fileWriter.close();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }
    }
}